# -*- coding: utf-8 -*- 
from flask import Blueprint, jsonify, request
from michelangelo.database import db_session, Sms, Template
from michelangelo.util import Result
import logging, json

mod = Blueprint('general', __name__)
logger = logging.getLogger('Michelangelo')


"""
    url
      /send-sms
    param
      phone: string; required; target phone to send sms
      content: string; required; content to send (yunpina should create the template in yupian admin platform)
      schedule_seconds: string; optional; default is 0, send immediately
    TODO
      request param validate to construct result
"""
@mod.route('/send-sms', methods=['GET', 'POST'])
def send_sms():
  args = request.args if request.method == 'GET' else request.form
  phone = args.get('phone')
  content = args.get('content')
  schedule_seconds = int(args.get('schedule_seconds', 0))
  logger.info('send message to phone {0}, content {1}, schedule_seconds {2}'.format(phone, content.encode('UTF-8'), schedule_seconds))
  sms = Sms(phone, content, schedule_seconds)
  db_session.add(sms)
  db_session.commit()
  return json.dumps(Result().success().set_message('success').to_dict())


"""
    url
      /get-template
    param
      template_id: Long; required; template id
"""
@mod.route('/get-template', methods=['GET', 'POST'])
def get_template():
  args = request.args if request.method == 'GET' else request.form
  template_id = long(args.get('template_id'))
  template = Template.query.filter(Template.template_id == template_id).first()
  if template:
    data = {'template_id': template.template_id, 'content': template.content.encode('UTF-8')}
    return json.dumps(Result().success().set_data(data).set_message('success').to_dict(), ensure_ascii=False)
  else:
    return json.dumps(Result().fail().set_message('template not found').to_dict())
